package com.xiaohai.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xiaohai.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:JwtUtil
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/1/22 16:36
 * @Version 1.0
 */
@Slf4j
public class JwtUtil {
    private final static int expiration = 20;
    private final static String secret = "xiaohai";

    /**
     * 生成token
     *
     * @param account
     * @param password
     * @return
     */
    public static String createToken(String account, String password) {
        HashMap<String, String> map = new HashMap<>();
        map.put("account", account);
        map.put("password", password);
        return JWT.create().withClaim("user", map).withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiration))).sign(Algorithm.HMAC256(secret));
    }

    public static Map<String, Object> verify(String token) {

        Map<String, Object> user = null;
        try {
            user = JWT.require(Algorithm.HMAC256(secret)).build().verify(token).getClaim("user").asMap();
        } catch (Exception e) {
            throw new CustomException("token过期");
        }
        return user;
    }
}
